package com.example.smartagrisys.controller;

import com.example.smartagrisys.common.Result;
import com.example.smartagrisys.dto.NotificationDTO;
import com.example.smartagrisys.entity.Notification;
import com.example.smartagrisys.service.NotificationService;
import com.example.smartagrisys.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 消息通知控制器
 */
@RestController
@RequestMapping("/notifications")
public class NotificationController {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private NotificationService notificationService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取当前用户的消息列表
     */
    @GetMapping
    public Result<List<NotificationDTO>> getUserNotifications(@RequestHeader("Authorization") String token) {
        System.out.println("===== NotificationController.getUserNotifications =====");
        System.out.println("接收到Authorization头: " + (token != null ? "长度=" + token.length() : "null"));
        
        if (token == null || !token.startsWith("Bearer ")) {
            System.out.println("Authorization头格式不正确，无法提取token");
            return Result.error("未提供有效token");
        }
        
        try {
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            System.out.println("提取的JWT Token: " + (jwtToken.length() > 20 ? jwtToken.substring(0, 20) + "..." : jwtToken));
            
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            System.out.println("解析出的用户ID: " + userId);
            
            if (userId == null) {
                System.out.println("未能从token中提取用户ID");
                return Result.error("未登录或token已过期");
            }
            
            List<Notification> notifications = notificationService.getUserNotifications(userId);
            System.out.println("获取到" + notifications.size() + "条通知");
            
            List<NotificationDTO> dtoList = notifications.stream().map(this::convertToDTO).collect(Collectors.toList());
            return Result.success(dtoList);
        } catch (Exception e) {
            System.out.println("获取通知列表时发生异常: " + e.getClass().getName() + " - " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取通知失败: " + e.getMessage());
        }
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread/count")
    public Result<Integer> getUnreadCount(@RequestHeader("Authorization") String token) {
        System.out.println("===== NotificationController.getUnreadCount =====");
        
        if (token == null || !token.startsWith("Bearer ")) {
            System.out.println("Authorization头格式不正确，无法提取token");
            return Result.error("未提供有效token");
        }
        
        try {
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                System.out.println("未能从token中提取用户ID");
                return Result.error("未登录或token已过期");
            }
            
            int count = notificationService.countUnreadNotifications(userId);
            System.out.println("用户" + userId + "有" + count + "条未读通知");
            return Result.success(count);
        } catch (Exception e) {
            System.out.println("获取未读通知数量时发生异常: " + e.getClass().getName() + " - " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取未读通知数量失败: " + e.getMessage());
        }
    }

    /**
     * 标记消息为已读
     */
    @PutMapping("/{id}/read")
    public Result<Boolean> markAsRead(@PathVariable("id") Long notificationId, 
                                    @RequestHeader("Authorization") String token) {
        System.out.println("===== NotificationController.markAsRead =====");
        
        if (token == null || !token.startsWith("Bearer ")) {
            System.out.println("Authorization头格式不正确，无法提取token");
            return Result.error("未提供有效token");
        }
        
        try {
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                System.out.println("未能从token中提取用户ID");
                return Result.error("未登录或token已过期");
            }
            
            boolean success = notificationService.markAsRead(notificationId, userId);
            return success ? Result.success(true) : Result.error("操作失败");
        } catch (Exception e) {
            System.out.println("标记消息已读时发生异常: " + e.getClass().getName() + " - " + e.getMessage());
            e.printStackTrace();
            return Result.error("标记消息已读失败: " + e.getMessage());
        }
    }

    /**
     * 标记所有消息为已读
     */
    @PutMapping("/read/all")
    public Result<Boolean> markAllAsRead(@RequestHeader("Authorization") String token) {
        System.out.println("===== NotificationController.markAllAsRead =====");
        
        if (token == null || !token.startsWith("Bearer ")) {
            System.out.println("Authorization头格式不正确，无法提取token");
            return Result.error("未提供有效token");
        }
        
        try {
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                System.out.println("未能从token中提取用户ID");
                return Result.error("未登录或token已过期");
            }
            
            boolean success = notificationService.markAllAsRead(userId);
            return success ? Result.success(true) : Result.error("操作失败");
        } catch (Exception e) {
            System.out.println("标记所有消息已读时发生异常: " + e.getClass().getName() + " - " + e.getMessage());
            e.printStackTrace();
            return Result.error("标记所有消息已读失败: " + e.getMessage());
        }
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteNotification(@PathVariable("id") Long notificationId, 
                                           @RequestHeader("Authorization") String token) {
        System.out.println("===== NotificationController.deleteNotification =====");
        
        if (token == null || !token.startsWith("Bearer ")) {
            System.out.println("Authorization头格式不正确，无法提取token");
            return Result.error("未提供有效token");
        }
        
        try {
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                System.out.println("未能从token中提取用户ID");
                return Result.error("未登录或token已过期");
            }
            
            boolean success = notificationService.deleteNotification(notificationId, userId);
            return success ? Result.success(true) : Result.error("操作失败");
        } catch (Exception e) {
            System.out.println("删除消息时发生异常: " + e.getClass().getName() + " - " + e.getMessage());
            e.printStackTrace();
            return Result.error("删除消息失败: " + e.getMessage());
        }
    }

    /**
     * 清空所有消息
     */
    @DeleteMapping("/clear")
    public Result<Boolean> clearAllNotifications(@RequestHeader("Authorization") String token) {
        System.out.println("===== NotificationController.clearAllNotifications =====");
        
        if (token == null || !token.startsWith("Bearer ")) {
            System.out.println("Authorization头格式不正确，无法提取token");
            return Result.error("未提供有效token");
        }
        
        try {
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                System.out.println("未能从token中提取用户ID");
                return Result.error("未登录或token已过期");
            }
            
            boolean success = notificationService.clearAllNotifications(userId);
            return success ? Result.success(true) : Result.error("操作失败");
        } catch (Exception e) {
            System.out.println("清空所有消息时发生异常: " + e.getClass().getName() + " - " + e.getMessage());
            e.printStackTrace();
            return Result.error("清空所有消息失败: " + e.getMessage());
        }
    }

    /**
     * 创建测试通知（仅用于开发阶段）
     */
    @PostMapping("/test")
    public Result<NotificationDTO> createTestNotification(@RequestHeader("Authorization") String token,
                                                    @RequestBody Map<String, String> params) {
        System.out.println("===== NotificationController.createTestNotification =====");
        
        if (token == null || !token.startsWith("Bearer ")) {
            System.out.println("Authorization头格式不正确，无法提取token");
            return Result.error("未提供有效token");
        }
        
        try {
            String jwtToken = token.substring(7); // 去掉"Bearer "前缀
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                System.out.println("未能从token中提取用户ID");
                return Result.error("未登录或token已过期");
            }
            
            String title = params.getOrDefault("title", "测试通知");
            String content = params.getOrDefault("content", "这是一条测试通知，用于开发测试。");
            String type = params.getOrDefault("type", "system");
            
            Notification notification = notificationService.createSystemNotification(userId, title, content, type);
            return Result.success(convertToDTO(notification));
        } catch (Exception e) {
            System.out.println("创建测试通知时发生异常: " + e.getClass().getName() + " - " + e.getMessage());
            e.printStackTrace();
            return Result.error("创建测试通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 将实体转换为DTO
     */
    private NotificationDTO convertToDTO(Notification notification) {
        NotificationDTO dto = new NotificationDTO();
        BeanUtils.copyProperties(notification, dto);
        
        // 格式化时间
        if (notification.getCreateTime() != null) {
            dto.setTime(notification.getCreateTime().format(DATE_FORMATTER));
        }
        
        return dto;
    }
} 